package mviewer.renderer.software.shader;

import mviewer.renderer.software.interfaces.ILighting;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Color;
import java.awt.GradientPaint;
import mviewer.renderer.software.interfaces.IBuffer;
import mviewer.renderer.software.interfaces.IShader;
import mviewer.types.IPolygon;
import mviewer.types.IVector;
import mviewer.types.IVertex;

public class SimpleGouraudShader implements IShader {

	@Override
	public void drawPolygon(Graphics g, IPolygon p3, Polygon p2
			, ILighting light, IBuffer buffer) {
		// get point colors
		IVertex[] v = p3.getVertices();
		IVector[] n = new IVector[v.length];
		for (int i = 0; i < v.length; i++)
			n[i] = v[i].getNormal();
		Color[] clr = new Color[] {light.renderColor(v[0], n[0], p3.getMaterial()),
						   light.renderColor(v[1], n[1], p3.getMaterial()),
						   light.renderColor(v[2], n[2], p3.getMaterial())};
		float[] cHSB;
		int bot=0, top=clr.length-1;
		float lower=Float.MAX_VALUE, higher=Float.MIN_VALUE;
		for (int i=0; i<clr.length; i++) {
			cHSB = Color.RGBtoHSB(clr[i].getRed(), clr[i].getGreen(), clr[i].getBlue(), (new float[3]));
			if (cHSB[2]<lower) {
				lower = cHSB[2];
				bot = i;
			}
			if (cHSB[2]>higher) {
				higher = cHSB[2];
				top = i;
			}
		}
		((Graphics2D)g).setPaint(
			new GradientPaint(p2.xpoints[top], p2.ypoints[top], clr[top]
				, p2.xpoints[bot], p2.ypoints[bot], clr[bot]));
		g.fillPolygon(p2);
	}
}
